"use client"

import { useState } from "react"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Switch } from "@/components/ui/switch"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Card } from "@/components/ui/card"
import { Trash2, Plus, ChevronDown, ChevronRight } from "lucide-react"
import type { NodeParameter } from "@/lib/node-configs"

interface ParameterValue {
  [key: string]: any
}

interface NodeParameterEditorProps {
  parameters: NodeParameter[]
  values: ParameterValue
  onChange: (values: ParameterValue) => void
  title: string
  type: "input" | "output"
  readonly?: boolean
}

export function NodeParameterEditor({
  parameters,
  values,
  onChange,
  title,
  type,
  readonly = false,
}: NodeParameterEditorProps) {
  const [expanded, setExpanded] = useState(true)

  const handleValueChange = (paramName: string, newValue: any) => {
    if (readonly) return
    onChange({
      ...values,
      [paramName]: newValue,
    })
  }

  const renderParameterInput = (param: NodeParameter) => {
    const value = values[param.name] ?? param.defaultValue

    switch (param.type) {
      case "string":
      case "email":
      case "url":
        return (
          <Input
            value={value || ""}
            onChange={(e) => handleValueChange(param.name, e.target.value)}
            placeholder={param.placeholder}
            disabled={readonly || type === "output"}
            className="text-sm"
          />
        )

      case "number":
        return (
          <Input
            type="number"
            value={value || ""}
            onChange={(e) => handleValueChange(param.name, parseFloat(e.target.value) || 0)}
            placeholder={param.placeholder}
            disabled={readonly || type === "output"}
            min={param.validation?.min}
            max={param.validation?.max}
            className="text-sm"
          />
        )

      case "boolean":
        return (
          <div className="flex items-center space-x-2">
            <Switch
              checked={value || false}
              onCheckedChange={(checked) => handleValueChange(param.name, checked)}
              disabled={readonly || type === "output"}
            />
            <span className="text-sm text-muted-foreground">{value ? "是" : "否"}</span>
          </div>
        )

      case "select":
        return (
          <Select
            value={value || param.defaultValue}
            onValueChange={(newValue) => handleValueChange(param.name, newValue)}
            disabled={readonly || type === "output"}
          >
            <SelectTrigger className="text-sm">
              <SelectValue placeholder={param.placeholder || "请选择"} />
            </SelectTrigger>
            <SelectContent>
              {param.options?.map((option) => (
                <SelectItem key={option.value} value={option.value}>
                  {option.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        )

      case "text":
      case "json":
        return (
          <Textarea
            value={value || ""}
            onChange={(e) => handleValueChange(param.name, e.target.value)}
            placeholder={param.placeholder}
            disabled={readonly || type === "output"}
            className="text-sm font-mono min-h-[80px]"
            rows={4}
          />
        )

      case "object":
      case "array":
        return (
          <Textarea
            value={typeof value === "string" ? value : JSON.stringify(value, null, 2)}
            onChange={(e) => {
              try {
                const parsed = JSON.parse(e.target.value)
                handleValueChange(param.name, parsed)
              } catch {
                handleValueChange(param.name, e.target.value)
              }
            }}
            placeholder={param.placeholder || (param.type === "array" ? "[]" : "{}")}
            disabled={readonly || type === "output"}
            className="text-sm font-mono min-h-[80px]"
            rows={4}
          />
        )

      case "datetime":
        return (
          <Input
            type="datetime-local"
            value={value || ""}
            onChange={(e) => handleValueChange(param.name, e.target.value)}
            disabled={readonly || type === "output"}
            className="text-sm"
          />
        )

      default:
        return (
          <Input
            value={value || ""}
            onChange={(e) => handleValueChange(param.name, e.target.value)}
            placeholder={param.placeholder}
            disabled={readonly || type === "output"}
            className="text-sm"
          />
        )
    }
  }

  if (parameters.length === 0) {
    return null
  }

  return (
    <Card className="p-3">
      <button
        onClick={() => setExpanded(!expanded)}
        className="w-full flex items-center justify-between mb-2 hover:opacity-70 transition-opacity"
      >
        <div className="flex items-center gap-2">
          {expanded ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
          <h4 className="font-semibold text-sm">{title}</h4>
          <Badge variant="secondary" className="text-xs">
            {parameters.length}
          </Badge>
        </div>
      </button>

      {expanded && (
        <div className="space-y-3 mt-2">
          {parameters.map((param) => (
            <div key={param.name} className="space-y-1.5">
              <div className="flex items-center justify-between">
                <Label className="text-sm font-medium">
                  {param.label}
                  {param.required && <span className="text-destructive ml-1">*</span>}
                </Label>
                <Badge variant="outline" className="text-xs">
                  {param.type}
                </Badge>
              </div>
              {param.description && <p className="text-xs text-muted-foreground">{param.description}</p>}
              {renderParameterInput(param)}
              {param.validation?.message && (
                <p className="text-xs text-muted-foreground italic">{param.validation.message}</p>
              )}
            </div>
          ))}
        </div>
      )}
    </Card>
  )
}

interface ParameterListProps {
  parameters: NodeParameter[]
  title: string
}

export function ParameterList({ parameters, title }: ParameterListProps) {
  const [expanded, setExpanded] = useState(true)

  if (parameters.length === 0) {
    return null
  }

  return (
    <Card className="p-3">
      <button
        onClick={() => setExpanded(!expanded)}
        className="w-full flex items-center justify-between mb-2 hover:opacity-70 transition-opacity"
      >
        <div className="flex items-center gap-2">
          {expanded ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
          <h4 className="font-semibold text-sm">{title}</h4>
          <Badge variant="secondary" className="text-xs">
            {parameters.length}
          </Badge>
        </div>
      </button>

      {expanded && (
        <div className="space-y-2 mt-2">
          {parameters.map((param) => (
            <div key={param.name} className="border rounded-md p-2 bg-muted/30">
              <div className="flex items-center justify-between mb-1">
                <span className="text-sm font-medium">
                  {param.label}
                  {param.required && <span className="text-destructive ml-1">*</span>}
                </span>
                <Badge variant="outline" className="text-xs">
                  {param.type}
                </Badge>
              </div>
              {param.description && <p className="text-xs text-muted-foreground mt-1">{param.description}</p>}
              {param.defaultValue !== undefined && (
                <p className="text-xs text-muted-foreground mt-1">
                  默认值: <code className="bg-muted px-1 rounded">{JSON.stringify(param.defaultValue)}</code>
                </p>
              )}
            </div>
          ))}
        </div>
      )}
    </Card>
  )
}
